import { Input } from 'antd';
import React, { useState } from 'react';
import useSubmit from '../../PublicHooks/useSubmit';
import { services } from '../../PublicServices/global';
import regx from '../../PublicUtils/regx';
import { codeTypes } from './enum';

const paramDef = {
  waitRun: true,
};
if (process.env.NODE_ENV !== 'production') {
  paramDef.StrValue = 'Self';
}

const CodeInput = ({
  onChange,
  value,
  phone,
  type = codeTypes.register,
  className,
}) => {
  Object.assign(paramDef, {
    type,
    phone,
  });

  const [count, setCount] = useState(0);
  const isPhone = type === codeTypes.findPwd || regx.isMobileNumber.test(phone);
  let interval;

  const getCode = useSubmit(
    services.getCaptcha,
    ({ Seconds, Num }) => {
      Seconds && setCount(Seconds);
      Num && onChange(Num);
      setInterval(() => {
        if (Seconds > 0) {
          Seconds--;
          setCount(Seconds);
        } else {
          clearInterval(interval);
        }
      }, 1000);
    },
    () => {
      interval && clearInterval(interval);
    },
  );

  const handleGetCode = () => isPhone && !count && getCode(paramDef);

  return (
    <>
      <Input className={className} value={value} onChange={onChange} />
      <span
        onClick={handleGetCode()}
        className={`${isPhone ? 'red' : 'gray'}`}
        style={{
          position: 'absolute',
          right: '14px',
          cursor: `${isPhone && !count ? 'pointer' : 'not-allowed'}`,
        }}
      >
        {count ? `${count}s` : '获取验证码'}
      </span>
    </>
  );
};

export default CodeInput;
